<?php

namespace Zders\CustomTools\Classes\Traits;

use Input;
use Lang;
use Flash;
use Backend\Classes\Controller;

trait RowBoot {
    /**
     * listtype init
     *
     * @return void
     */
    public function boot()
    {
        /**
         * 自定义行内操作处理函数
         */
        Controller::extend(function ($controller) {

            $controller->addCss('/plugins/zders/customtools/assets/css/partials/customtools.css', 'core');
            $controller->addJs('/plugins/zders/customtools/assets/js/_customtools.js', 'core');

            $controller->addDynamicMethod('index_onUpdate', function () use ($controller) {
                if (method_exists($controller, 'onUpdate')) {
                    return call_user_func_array([$controller->controller, 'onUpdate'], func_get_args());
                }

                $listConfig = $controller->listGetConfig();

                $listModel = new $listConfig->modelClass;

                $query = $listModel->newQuery();
                $key = $listModel->getKeyName();

                if (!Input::has($key)) {
                    Flash::error(Lang::get('zders.customtools::lang.partials.switch.update_param_err_msg', ['key'=>$key]));
                    return ;
                }
                $query->where($key, Input::get($key));

                /*
                * Update record
                */
                $record = $query->get();

                if ($record) {
                    $data = Input::get();
                    unset($data[$key]);
                    $query->update($data);

                    Flash::success(Lang::get('zders.customtools::lang.partials.switch.update_success_msg'));
                    return ;
                }
                else {
                    Flash::error(Lang::get('zders.customtools::lang.partials.switch.update_error_msg'));
                    return ;
                }
            });
        });
    }
}
